package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.infore.airsupervise.R;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.MissionE;
import com.infore.airsupervise.bean.PolluterE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.MissionBiz;
import com.infore.airsupervise.biz.impl.MissionBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.other.listener.DateAndTimeBiz;
import com.infore.airsupervise.other.listener.DateAndTimeBizImpl;
import com.infore.airsupervise.other.listener.DateAndTimeListener;
import com.infore.airsupervise.ui.fragment.MissionFileSelectFragment;
import com.infore.airsupervise.ui.fragment.PsonSelectorFragment;
import com.infore.airsupervise.ui.fragment.RecorderDiscribFragment;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.DialogUtil;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.rey.material.app.DatePickerDialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.widget.CheckBox;
import com.rey.material.widget.RadioButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * @features: 新的任务指派界面
 * @author: WuTao
 * @date: 2017/5/6 14:06
 */
public class NewMissionCreateActivity extends BaseTitleBarActivity {
    @BindView(R.id.et_create_title)
    EditText etCreateTitle;
    @BindView(R.id.et_pson_push)
    EditText etPsonPush;
    @BindView(R.id.tv_pson_examine)
    TextView tvPsonExamine;
    @BindView(R.id.tv_endTime)
    TextView tvEndTime;
    @BindView(R.id.cb_source)
    CheckBox cbSource;
    @BindView(R.id.ll_source_control)
    LinearLayout llSourceControl;
    @BindView(R.id.rv_source_list)
    RecyclerView rvSourceList;
    @BindView(R.id.ll_pson_examine)
    LinearLayout llPsonExamine;
    @BindView(R.id.rb_true)
    RadioButton rbTrue;
    @BindView(R.id.rb_false)
    RadioButton rbFalse;

    private PsonSelectorFragment psonSelectorFra; //人员选择
    private  RecorderDiscribFragment recorderDiscribFra; // 录音与描述
    private MissionFileSelectFragment fileSelectFra ; // 附件选择

    private UserE userE;
    private List<PolluterE> polluterEList;
    private BaseQuickAdapter<PolluterE,BaseViewHolder> polluterAdapter ;

    private MissionBiz missionBiz;
    private MissionE missionE;
    private DateAndTimeBiz dateAndTimeBiz;//时间选择器



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mission_create);
        getWindow().setBackgroundDrawable(null);
        ButterKnife.bind(this);

        missionBiz = new MissionBizImpl();
        title.setText("发布任务");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_CHECK);
        polluterEList = new ArrayList<>();
        initView();

    }

    /**
     * 初始化控件
     */
    private void initView() {
        //发布人
        userE = UserE.getUserInfo();
        missionE = new MissionE();
        etPsonPush.setText(userE.getRealName());
        //关联污染源
        cbSource.setOnCheckedChangeListener(checkListener);
        //审核
        rbTrue.setOnCheckedChangeListener(checkListener);
        rbFalse.setOnCheckedChangeListener(checkListener);
        //选择处理人
         psonSelectorFra = new PsonSelectorFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_mission_psons,psonSelectorFra,null).commit();
        //录音
         recorderDiscribFra = new RecorderDiscribFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_mission_discrib,recorderDiscribFra,null).commit();
        //附件
        fileSelectFra = new MissionFileSelectFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_files,fileSelectFra,null).commit();
        initSourceRecycle();
    }

    /**
     * 关联的污染源列表
     */
    private void initSourceRecycle(){
        rvSourceList.setLayoutManager( new LinearLayoutManager(ctx));
        polluterAdapter = new BaseQuickAdapter<PolluterE, BaseViewHolder>(R.layout.item_selector,polluterEList) {
            @Override
            protected void convert(final BaseViewHolder helper, PolluterE item) {
                helper.setText(R.id.tv_title,item.getName());
                ImageView delete= helper.getView(R.id.iv_delete);
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        polluterAdapter.remove(helper.getAdapterPosition());
                    }
                });
            }
        };
        rvSourceList.setAdapter(polluterAdapter);
    }

    /**
     * 提交任务
     */
    private void commitMission(){
        //loading dialog
        final SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        //设置任务参数
        missionE.setTitle(etCreateTitle.getText().toString());
        missionE.setLastTime(tvEndTime.getText().toString());
        missionE.setIssueTime(DateUtil.getCurrentDateStr(true));
        missionE.setIsApproved(rbTrue.isChecked() ? 1: 0);//是否需要审核： 1 需要/0 不需要
        missionE.setDiscrib(recorderDiscribFra.getDiscrib());
        missionE.setHandlePsonId(psonSelectorFra.gethandlePsonId());
        missionE.setVoice(recorderDiscribFra.getvoicePath());
        missionE.setLeaderId(psonSelectorFra.getLeaderId());

        missionE.setFile(fileSelectFra.getFileList());
        String mn = "";
        for(int i = 0 ;i<polluterEList.size() ; i++){
            mn+=polluterEList.get(i).getMn();
            if(i<polluterEList.size()-1){
                mn+=",";
            }
        }
        missionBiz.sendMissionCommitRequest(mn, userE.getUserId(), missionE
                , new OnServerResponseListener<BaseResponse>() {
            @Override
            public void onSucceed(BaseResponse result, String desc) {
                //成功提示dialog
                dialog.setTitleText(MsgConst.OPERATION_SUCCESS)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                               finish();
                            }
                        })
                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                //失败提示dialog
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }

    /**
     * 时间选择
     */
    private void setEndTime() {
        if(null == dateAndTimeBiz){
            dateAndTimeBiz = new DateAndTimeBizImpl();
        }
        dateAndTimeBiz.getDatePicker(getSupportFragmentManager(), new DateAndTimeListener() {
            @Override
            public void getDateAndTimeString(String dateAndTime) {
                tvEndTime.setText(dateAndTime);
            }
        });
    }


    @Override
    protected void onRightMenuClick(View view) {
        String str_alarm = "";
        if (etCreateTitle.getText().toString().isEmpty()) {
            str_alarm = "任务名称不能为空";
        } else if (tvEndTime.getText().toString().isEmpty()) {
            str_alarm = "截止日期不能为空";
        }  else if(TextUtils.isEmpty(psonSelectorFra.getLeaderId())){
            str_alarm = "请选择处理人";
        }else {
            commitMission();
            return;
        }
        ToastUtil.showShort(ctx, str_alarm);

    }

    @OnClick({R.id.btn_examine, R.id.tv_endTime, R.id.source_selector})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_examine:
                JumpUtil.ForResultJumpFromTo(this,PsonContactActivity.class,300,Constants.INTENT_INT_KEY,1);
                break;
            case R.id.tv_endTime: //截止日期
                setEndTime();
                break;
            case R.id.source_selector://选择污染源
                JumpUtil.ForResultJumpFromTo(this,PolluterSearchActivity.class,200, Constants.INTENT_INT_KEY,1);
                break;
        }
    }

    /**
     * 关联污染源 布局显示隐藏
     */
    private CompoundButton.OnCheckedChangeListener checkListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            switch (compoundButton.getId()){
                case R.id.cb_source :
                    llSourceControl.setVisibility(b ? View.VISIBLE : View.GONE);
                    break;
                case R.id.rb_false :
                case R.id.rb_true :
                    if(b){
                        rbFalse.setChecked(rbFalse == compoundButton);
                        rbTrue.setChecked(rbTrue == compoundButton);
                        llPsonExamine.setVisibility(rbTrue == compoundButton ?View.VISIBLE : View.GONE);
                    }
                    break;
            }
        }
    };

    boolean isFirst = true; //不重复添加
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if( resultCode == RESULT_OK){
            if(requestCode == 200){
                PolluterE item = (PolluterE) data.getSerializableExtra(Constants.INTENT_OBJ_KEY);
                for(PolluterE  e : polluterEList){
                    if(TextUtils.equals(e.getMn(),item.getMn())){
                        isFirst = false;
                        return ;
                    }
                }
                if(isFirst){
                    polluterEList.add(item);
                    polluterAdapter.notifyDataSetChanged();
                }else{
                    isFirst = true;
                }
            }else if(requestCode ==300){
                UserE userE = (UserE) data.getSerializableExtra(Constants.INTENT_OBJ_KEY);
                tvPsonExamine.setText(userE.getRealName());
                missionE.setApprovePson(userE.getUserId());
            }

        }
    }
}
